package com.google.code.yargon.util;

import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 * Singleton property container
 * 
 * @author Mika Myllynen
 *
 */
public class PropertyUtil {
	
	// Property filename
	private static final String PROPERTY_FILE = "yargon.properties";
	
	// Singleton instance of this class
	private static PropertyUtil instance = null;

	// Properties wrapped by this class
	private static Properties props = null;
	
	/**
	 * Creates a singleton instance of this class
	 * 
	 * @return PropertyUtil instance
	 */
	public static PropertyUtil getInstance() {
		if(null == instance) {
			instance = new PropertyUtil(PROPERTY_FILE);
		} 
		return instance;
	}
	
	/**
	 * Loads properties from file, file must be in classpath
	 * 
	 * @param propertyFile
	 */
	private PropertyUtil(String propertyFile) {
		props = new Properties();
	
		try {
			ClassLoader cl = Thread.currentThread().getContextClassLoader(); 
			InputStream s = cl.getResourceAsStream(propertyFile);
	
			if (s == null) {
				System.err.println("Cannot locate property file: " +propertyFile);
			}
			else {
				props.load(s);
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	
		// Now is good time to initialize logger
		Logger log = LogUtil.getInstance(props);
		log.debug("Properties and logger initialized.");
	}
	
	/**
	 * Get integer from properties
	 * 
	 * @param property
	 * @return configured value or Integer.MIN_VALUE
	 */
	public int getInt(String property) {
		String v = props.getProperty(property);
		
		if(null != v) {
			return Integer.parseInt(v);
		}
		return Integer.MIN_VALUE;
	}
	
	/**
	 * Get string from property file
	 * 
	 * @param property
	 * @return configured value or null
	 */
	public String getString(String property) {
		return props.getProperty(property);
	}
	
	/**
	 * Return everything as Properties object 
	 * 
	 * @return
	 */
	public Properties getProperties() {
		return props;
	}
}

